﻿using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Shapes;
using WK.Libraries.BetterFolderBrowserNS.Helpers;
using Path = System.IO.Path;

namespace Games_0623
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        List<MyDataObject> myDataObjects = new List<MyDataObject>();
        string lastSelectPath = string.Empty;
        string lastSavePath = @"C:\";
        string tagName = "hot";
        string synopsisContent = string.Empty;
        public MainWindow()
        {
            InitializeComponent();
            this.MouseLeftButtonDown += MainWindow_MouseLeftButtonDown;
            this.btnClose.Click += (se, ee) => {
                this.Close();
            };
            this.btnMax.Checked += (se, ee) => {
                this.WindowState = WindowState.Maximized;
                this.btnMax.Content = "\ue621";
            };
            this.btnMax.Unchecked += (se, ee) => {
                this.WindowState = WindowState.Normal;
                this.btnMax.Content = "\ue690";
            };
            this.btnMin.Click += (se, ee) => {
                this.WindowState = WindowState.Minimized;
            };
            this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
            this.MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
            this.btnOpen.Click += BtnOpen_Click;
        }

        #region v1_0530
        private void BtnOpen_Click(object sender, RoutedEventArgs e)
        {
            myDataObjects.Clear();
            OutputText.Text = "";
            BetterFolderBrowserDialog folderBrowserDialog = new BetterFolderBrowserDialog();
            folderBrowserDialog.Title = "选择文件夹";
            folderBrowserDialog.InitialDirectory = "C:\\";
            folderBrowserDialog.ShowDialog();
            if (folderBrowserDialog.FileName == string.Empty) {
                MessageBox.Show("请选择文件夹");
                return;
            }
            curId = string.IsNullOrEmpty(numberText.Text) ? 0 : int.Parse(numberText.Text) - 1;
            text.Text = lastSelectPath = folderBrowserDialog.FileName;
            listDirectory(lastSelectPath.Trim());

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "json files (*.json)|*.json";
            saveFileDialog.Title = "Save File";
            saveFileDialog.InitialDirectory = lastSavePath;
            saveFileDialog.FileName = "gamedata.json";
            var result = saveFileDialog.ShowDialog();
            if (result != null && (bool)result) {
                // 用户点击保存按钮
                // 可以通过saveFileDialog1.FileName获取用户选择的文件路径
                lastSavePath = saveFileDialog.FileName;
                string updatedJsonText = JsonConvert.SerializeObject(myDataObjects);
                File.WriteAllText(Path.Combine(saveFileDialog.FileName), updatedJsonText);
                OutputText.Text = updatedJsonText;
            }
        }
        int curId = 0;
        bool isIconFist = false;
        string folderName = string.Empty;

        string iconPath = "https://localhost/projectGame/games/";
        /// <summary>
        /// 列出path路径对应的文件夹中的子文件夹和文件
        /// 然后再递归列出子文件夹内的文件和文件夹
        /// </summary>
        /// <param name="path">需要列出内容的文件夹的路径</param>
        /// <param name="leval">当前递归层级，用于控制输出前导空格的数量</param>
        private void listDirectory(string path)
        {
            try {
                DirectoryInfo theFolder = new DirectoryInfo(@path);
                //遍历文件
                foreach (FileInfo NextFile in theFolder.GetFiles()) {
                    if ("icons" == theFolder.Name.ToLower()) {
                        var iconpath = folderName + "/" + theFolder.Name + "/" + NextFile.Name;
                        if (!isIconFist) {
                            isIconFist = true;
                        }
                        myDataObjects.Add(new MyDataObject() {
                            id = curId,
                            url = "games/1599.html",
                            category = "Hot Games",
                            key = "Hot",
                            title = folderName,
                            logo = iconPath + iconpath,
                            synopsis = synopsisContent,
                            tag = tagName
                        });
                    }
                }
                if (isIconFist) {
                    isIconFist = false;
                    return;
                }
                foreach (DirectoryInfo NextFolder in theFolder.GetDirectories()) {
                    foreach (DirectoryInfo SecondFolder in NextFolder.GetDirectories()) {
                        if ("config" == SecondFolder.Name.ToLower()) {
                            foreach (FileInfo NextFile in SecondFolder.GetFiles()) {
                                string json = File.ReadAllText(NextFile.FullName);
                                ConfigJsonData data = JsonConvert.DeserializeObject<ConfigJsonData>(json);
                                synopsisContent = data.description;
                            }
                        } else if ("icons" == SecondFolder.Name.ToLower()) {
                            folderName = NextFolder.Name;
                            curId++;
                            listDirectory(SecondFolder.FullName);
                        }
                    }
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion


        private void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void WriteJsonData(string titleName, string iconPath)
        {
            //// 读取JSON文件
            //string jsonText = File.ReadAllText("file.json");
            //var dataObject = JsonConvert.DeserializeObject<List<MyDataObject>>(jsonText);

            //// 修改数据
            //dataObject.Property1 = "new value";

            // 将修改后的数据写入JSON文件
            //string updatedJsonText = JsonConvert.SerializeObject(dataObject);
            //File.WriteAllText("file.json", updatedJsonText);
        }

        private void btnAddSM_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(text.Text)) {
                MessageBox.Show("请先打开游戏文件夹");
                return;
            }
            AddBeforeToIcons("sm-");
        }

        private void AddBeforeToIcons(string before)
        {
            DirectoryInfo theFolder = new DirectoryInfo(lastSelectPath);
            foreach (DirectoryInfo NextFolder in theFolder.GetDirectories()) {
                foreach (DirectoryInfo SecondFolder in NextFolder.GetDirectories()) {
                    if ("icons" == SecondFolder.Name.ToLower()) {
                        foreach (FileInfo NextFile in SecondFolder.GetFiles()) {
                            var folderName = NextFile.DirectoryName;
                            var fileName = NextFile.Name;
                            var newFileName = before + fileName;
                            if (theFolder.GetFiles().Any(x => x.Name == newFileName)) {
                                MessageBox.Show($"已存在{before}{newFileName}");
                            }
                            File.Copy(NextFile.FullName, Path.Combine(folderName, newFileName));
                        }
                        return;
                    }
                }
            }
        }

        private void btnAddMD_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(text.Text)) {
                MessageBox.Show("请先打开游戏文件夹");
                return;
            }
            AddBeforeToIcons("md-");
        }
    }

    //"id": 1,
    //"url": "games/1599.html",
    //"category": "Hot Games",
    //"key": "Hot",
    //"title": "2048Legend",
    //"datasrc": "http://localhost/projectGame/games/2048Legend/icons/icon-48x48.png"

    public class MyDataObject
    {
        public int id { get; set; }
        public string url { get; set; }
        public string category { get; set; }
        public string key { get; set; }
        public string title { get; set; }
        public string logo { get; set; }
        public string tag { get; set; }
        public string synopsis { get; set; }
    }

    public class ConfigJsonData
    {
        public string title { get; set; }
        public string description { get; set; }
    }
}
